package com.hxkj.client.service.taglib.config;

import com.google.common.collect.Maps;
import freemarker.cache.TemplateLoader;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Map;


/***
 * @desc String freemarker 解析器
 * @author yaosy
 * @date 2018年8月15日
 * **/
@Component
public class StringTemplateAnalyze implements TemplateLoader {

    private static final String DEFAULT_TEMPLATE_KEY = "_default_template_key";

    private Map templates = Maps.newConcurrentMap();


    public void addTemplate(String name,String template){
        if(name == null || template == null || name.equals("") || template.equals("")){
            return ;
        }
        if(!templates.containsKey(name)){
            templates.put(name, template);
        }
    }

    @Override
    public Object findTemplateSource(String name) throws IOException {
        if(name == null || name.equals("")) name = DEFAULT_TEMPLATE_KEY;
        return templates.get(name);
    }

    @Override
    public long getLastModified(Object templateSource) {
        return 0;
    }

    @Override
    public Reader getReader(Object templateSource, String encoding) throws IOException {
        return new StringReader((String) templateSource);
    }

    @Override
    public void closeTemplateSource(Object templateSource) throws IOException {

    }
}
